import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {NzImageService} from 'ng-zorro-antd/image';
import {PreviewOptionImgRemarkComponent} from '../preview-option-img-remark/preview-option-img-remark.component';
import {NzModalService} from 'ng-zorro-antd/modal';

// 题目
interface Question {
  id: string;
  questionName: string;
  edit: boolean;
  selectType: 0 | 1;
  isRequired: boolean;
  value: string; // 选中的值
  optionsFold: boolean; // 选项是否折叠
  show: boolean; // 选项是否可见
  options: Option[];
}

// 选项
interface Option {
  id: string; // id
  checked: boolean; // 选中状态
  optionName: string; // 选项名称
  selectAble: boolean; // 是否可选
  invalidCause: string; // 不可选理由
  used: boolean; // 是否是二手
  questionId: any; // 要跳转的题目的序号
  optionRemark: string; // 选项描述
  optionImages: []; // 选项图片
}

@Component({
  selector: 'app-preview-assess-price-template',
  templateUrl: './preview-assess-price-template.component.html',
  styleUrls: ['./preview-assess-price-template.component.scss']
})
export class PreviewAssessPriceTemplateComponent implements OnInit {
  // 显隐
  @Input() visible = false;
  // 所有要预览的原始数据
  @Input() questionList: any;
  // 模态框显隐
  @Output() visibleChange = new EventEmitter();
  // 显示的数据
  showList: Question[] = [];

  constructor(
    private nzImageService: NzImageService,
    private nzModalService: NzModalService,
  ) {
  }

  ngOnInit(): void {
    this.showList = JSON.parse(JSON.stringify(this.questionList));
    this.showList.forEach((q: any, index) => {
      q.options = q.options.map((o: any) => ({...o, checked: false}));
      q.optionsFold = false;
      q.show = index === 0;
    });
  }

  updateSingleChecked() {

  }

  // 单选
  singleChecked(questionIndex: number, value: any) {
    this.showList[questionIndex].optionsFold = true;
    // 是否要清空后面的题目选中状态
    let hide = false;
    // 是否要直接结束
    let end = false;
    this.showList[questionIndex].options.forEach((o: any) => {
      if (o.questionId) {
        hide = true;
      }
      if (o.id === value && o.questionId === 'end') {
        end = true;
      }
    });
    if (hide) {
      // 隐藏之后的选项
      this.showList.forEach((q: any, index) => {
        if (index > questionIndex) {
          q.show = false;
          q.optionsFold = false;
          q.value = '';
          q.options.forEach((o: any) => o.checked = false);
        }
      });
    }
    if (end) {
      return;
    }
    if (this.showList[questionIndex + 1]) {
      this.showList[questionIndex + 1].show = true;
    }
    this.showList[questionIndex].options.forEach(o => {
      if (o.id === value && o.questionId) {
        this.showList.forEach((q: any, index) => {
          if (index > questionIndex && index < this.showList.findIndex((q2: any) => q2.id === o.questionId)) {
            q.show = false;
          } else if (index === this.showList.findIndex((q2: any) => q2.id === o.questionId)) {
            q.show = true;
          }
        });
      }
    });
    this.checkNotRequired(questionIndex);
  }

  // 多选
  multipleChecked(questionIndex: number) {
    this.checkNotRequired(questionIndex);
    if (this.showList[questionIndex + 1]) {
      this.showList[questionIndex + 1].show = true;
    }
  }

  // 检查是否剩下的全是非必选项
  checkNotRequired(questionIndex: number) {
    if (this.showList.some((s, index) => s.isRequired && index > questionIndex)) {
    } else {
      this.showList.forEach((q: any, index) => {
        if (index > questionIndex) {
          q.show = true;
        }
      });
    }
  }

  // 改变折叠状态
  changeFold(question: Question) {
    question.optionsFold = !question.optionsFold;
  }

  // 隐藏预览模态框
  hidePreviewModal() {
    // this.visible = false;
    this.visibleChange?.emit();
  }

  // 获取选中的结果名称
  getResult(question: Question) {
    if (question.selectType === 0 && question.value) {
      return question.options.filter(o => o.id === question.value)[0].optionName;
    } else if (question.selectType === 1 && question.options.some(o => o.checked)) {
      return question.options.filter(o => o.checked).map(o => o.optionName).join(',');
    }
    return '';
  }

  // 所有必选项都选择了，显示评估按钮
  allRequiredIsChecked() {
    let complete = true;
    this.showList.forEach(q => {
      if (q.isRequired && q.show) {
        if (q.selectType === 0) {
          if (!q.value) {
            complete = false;
          }
        } else if (q.selectType === 1) {
          if (!q.options.some(o => o.checked)) {
            complete = false;
          }
        }
      }
    });
    return complete;
  }

  calcQuestionIndex(questionIndex: number) {
    return this.showList.filter((q, index) => (q.show && index <= questionIndex)).length;
  }


  // 显示选项描述和图片
  showOptionRemarkModal(question: any, option: any, $event: any) {
    let details: any[] = [];
    question.options.forEach((o: any) => {
      if (o.optionImages || o.optionRemark) {
        details = [...details, ...o.optionImages.split(',').map((v: any) => ({
          id: o.id,
          name: o.optionName,
          url: v,
          remark: o.optionRemark
        }))];
      }
    });
    const index = details.findIndex(d => d.id === option.id);
    const modal = this.nzModalService.create({
      nzTitle: question.questionName,
      nzContent: PreviewOptionImgRemarkComponent,
      nzComponentParams: {
        details,
        index
      },
      nzFooter: null,
      nzMaskClosable: true,
    });
    $event.stopPropagation();
    $event.preventDefault();
    $event.returnValue = false;
  }

  // 查看图片
  previewImage(src: string) {
    this.nzImageService.preview([{src, width: '400px', height: '400px'}], {nzZoom: 1.5, nzRotate: 0});
  }

  // 题目id转名称
  questionIdToName(id: string, questionList: any[]) {
    let result = id === 'end' ? '结束' : 'id转名称异常';
    questionList.forEach((q: any, index) => {
      if (q.id === id) {
        result = q.questionName;
      }
    });
    return result;
  }
}
